import request from "../../utils/request";

//本地的静态数据字典
const dict = {
  practiceModeList: [
    {
      value: "英考中",
      label: "英考中",
    },
    {
      value: "中考英",
      label: "中考英",
    },
  ],
};
export const dictActionType = {
  getters: {
    dict: "dict/dict",
  },
  mutations: {
    dict: "dict/dict",
  },
  actions: {
    dict: "dict/dict",
    getDictValueByLabel: "dict/getDictValueByLabel",
  },
};

export default {
  namespaced: false,
  state: {
    dict: null,
  },
  getters: {
    [dictActionType.getters.dict](state) {
      return state.dict;
    },
  },
  mutations: {
    [dictActionType.mutations.dict](state, dict) {
      state.dict = dict;
    },
  },
  actions: {
    //发送请求获取数据字典
    [dictActionType.actions.dict](store) {
      return new Promise((resolve, reject) => {
        if (store.getters[dictActionType.getters.dict]) {
          resolve(store.getters[dictActionType.getters.dict]);
        } else {
          request({
            url: "dict/getDictList",
            showLoading: true,
            errorHandle: true,
          })
            .then((data = {}) => {
              store.commit(dictActionType.mutations.dict, { ...data, ...dict });
              resolve(store.getters[dictActionType.getters.dict]);
            })
            .catch((err) => {
              reject(err);
            });
        }
      });
    },
    //通过label获取字典值
    [dictActionType.actions.getDictValueByLabel](store, params = { label: "", type: "" }) {
      return new Promise((resolve, reject) => {
        store
          .dispatch(dictActionType.actions.dict)
          .then((data) => {
            let dictItem = "";
            if (params.type) {
              dictItem = data[params.type].find((item) => {
                return item.label === params.label;
              });
            } else {
              for (let key in data) {
                dictItem = data[key].find((item) => {
                  return item.label === params.label;
                });
                if (dictItem) {
                  break;
                }
              }
            }
            resolve(dictItem.value);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
};
